#include "Heap.h"

#define _CRT_SECURE_NO_WARNINGS 1

void HeapInit(Heap* php)
{
	assert(php);
	php->size = php->capacity = 0;
	php->a = NULL;
}

void HeapDestory(Heap* php)
{
	assert(php);
	free(php);
	php->a = NULL;
	php->size = php->capacity = 0;
}

void HeapPrintf(Heap* php)
{
	assert(php);
	int i = 0;
	for (i = 0; i < php->size; i++)
	{
		printf("%d ", php->a[i]);
	}
	printf("\n");
}

void HeapPushBack(Heap* php, HeapDataType x)
{
	assert(php);
	if (php->size == php->capacity)
	{
		int newcapacity = php->capacity == 0 ? 4 : php->capacity * 2;
		HeapDataType* tmp = (HeapDataType*)realloc(php->a,sizeof(HeapDataType)*newcapacity);
		if (tmp == NULL)
		{
			perror("realloc fail");
			exit(-1);
		}
		php->capacity = newcapacity;
		php->a = tmp;
	}
	php->a[php->size] = x;
	php->size++;

	AdjustUp(php->a, php->size - 1);
}

void Swap(int* x, int* y)
{
	int* tmp = *x;
	*x = *y;
	*y = tmp;
}

void HeapPop(Heap* php)
{
	assert(php);
	assert(!HeapEmpty(php));
	Swap(php->a[0], php->a[php->size - 1]);
	php->size--;
	AdjustDown(php->a,php->size,0);
}

bool HeapEmpty(Heap* php)
{
	assert(php);
	return php->size == 0;
}

void AdjustDown(HeapDataType* a, int n, int parent)
{
	int minchild = parent * 2+1;
	while (minchild<n)
	{
		if (a[minchild] > a[minchild + 1]&&minchild+1<n)
		{
			minchild++;
		}
		if (a[minchild] > a[parent])
		{
			Swap(a[minchild], a[parent]);
			parent = minchild;
			minchild = parent * 2 + 1;
		}
		else
			break;
	}
}

void AdjustUp(HeapDataType* a, int child)
{
	int parent = (child - 1) / 2;
	while (child>0)
	{
		if (a[child] < a[parent])
		{
			Swap(&a[child], &a[parent]);
			child = parent;
			parent = (child - 1) / 2;
		}
		else
			break;
	}
}

int HeapSize(Heap* php)
{
	assert(php);
	return php->size;
}

HeapDataType HeapTop(Heap* php)
{
	assert(php);
	return php->a[0];
}
 